/* model */
import { RoleAuthSaveModel } from "@model/param/in/Role"
import { RoleViewFormModelType } from "@src/modules/account/roleModule/component/RoleViewForm"
import { AuthTreeNode } from '@src/modules/account/roleModule/component/AuthTree/model'
import Role, { RoleAuth } from '@model/entity/Role/Role'
import { SHBProductLineEnum } from "@shb-lib/tenant"

function transformToRoleAuthSaveModel(
  form: RoleViewFormModelType | Record<string, any>,
  authTreeData: AuthTreeNode[],
  roleId: string,
  productLine: SHBProductLineEnum
): RoleAuthSaveModel {
  
  const describe = form.description
  const name = form.name
  const authorityBOList: RoleAuth[] = []
  const qualificationIds = form.qualificationIds?.map(item=>item.value)
  
  authTreeData.forEach(node => {
    getAuthorityList(node, authorityBOList)
  })
  
  return {
    roleId,
    describe,
    name,
    authorityBOList,
    productLine,
    qualificationIds
  }
}

function getAuthorityList(authTreeNode: AuthTreeNode, data: RoleAuth[]) {
  
  const key = authTreeNode.key
  const isChecked = authTreeNode.checked
  const isLastLevel = authTreeNode.level == AuthTreeNode.lastLevel
  
  if (isChecked && isLastLevel) {
    data.push({
      authorityId: String(authTreeNode.id),
      depth: String(authTreeNode?.depth || ''),
    } as RoleAuth)
  }
  
  if (authTreeNode.children) {
    authTreeNode.children.forEach(node => {
      getAuthorityList(node, data)
    })
  }
  
}

export {
  transformToRoleAuthSaveModel
}

export default {
  transformToRoleAuthSaveModel
}